package com.msconfig.mvp.view.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.bean.deviceInfoBean.TagDeviceInfo;
import com.msconfig.bluetooth.BlueToothInit;
import com.msconfig.broadcast.BlueToothBroadcastReceiver;
import com.msconfig.device.CommandParseManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GeoLocationData;
import com.msconfig.event.BluetoothInfoEvent;
import com.msconfig.event.DeviceUpdateEvent;
import com.msconfig.event.ShowDeviceNameEvent;
import com.msconfig.mvp.view.activity.base.BaseMvpActivity;
import com.msconfig.mvp.view.activity.base.BasePresenter;
import com.msconfig.mvp.view.adapter.BlueToothDeviceAdapter;
import com.msconfig.mvp.view.fragment.ApplyConfigFragment;
import com.msconfig.mvp.view.fragment.ConnectioningDialogFragment;
import com.msconfig.mvp.view.fragment.EquipmentCommunicationSetupFragment;
import com.msconfig.mvp.view.fragment.EquipmentInformationFragment;
import com.msconfig.mvp.view.fragment.SatelliteFormFragment;
import com.msconfig.mvp.view.fragment.SatelliteLocateInformationFragment;
import com.msconfig.mvp.view.fragment.SatelliteMapFragment;
import com.msconfig.mvp.view.fragment.SaveConfigFragment;
import com.msconfig.mvp.view.fragment.SetupAboutFragment;
import com.msconfig.mvp.view.fragment.SetupDebugFragment;
import com.msconfig.mvp.view.fragment.SetupGprsFragment;
import com.msconfig.mvp.view.fragment.SetupOtherFragment;
import com.msconfig.mvp.view.fragment.SetupSurveyStationFragment;
import com.msconfig.mvp.view.fragment.SetupTransformationFragment;
import com.msconfig.mvp.view.fragment.SetupWifiFragment;
import com.msconfig.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import static com.msconfig.mvp.view.fragment.EquipmentCommunicationSetupFragment.LAST_DEVICE;


public class MainActivity extends BaseMvpActivity implements View.OnClickListener {
    private LinearLayout llEquipmentCommunicationSetup;
    private LinearLayout llSetupGprs;
    private LinearLayout llSetupWifi;
    private LinearLayout llSetupSurveyStation;
    private LinearLayout llSetupTransformation;
    private LinearLayout llSetupOther;
    private LinearLayout llSetupDebug;
    private LinearLayout llSetupAbout;
    private LinearLayout llEquipmentInformation;
    private LinearLayout llSatelliteLocateInformation;
    private LinearLayout llSatelliteForm;
    private LinearLayout llSatelliteMap;
    private LinearLayout llSaveConfig;
    private LinearLayout llApplyConfig;
    private TextView tvSatelliteNum;
    private TextView tvSolutionState;
    private TextView tvDelayTime;
    private TextView tvDataResultStatus;
    private TextView tvResultIp;
    private TextView tvResultPort;
    private GeoLocationData geoLocationData;
    private TagDeviceInfo deviceInfo;

    private TextView tvDeviceName;
    private BlueToothBroadcastReceiver blueToothBroadcastReceiver;
    private BluetoothAdapter mBtAdatper;
    private BlueToothInit operateBlueTooth;
    private Date date;
    private SimpleDateFormat simpleDateFormat;
    public Set<BluetoothDevice> bondedDevices;
    private BluetoothDevice device;
    private MyHandler myHandler;
    private ConnectioningDialogFragment connectioningDialogFragment;
    private SaveConfigFragment saveConfigFragment;
    boolean isSendSuccessFirst;
    private int rssi;
    protected static final int MSG_AUTO_CONNECT =0;//自动连接
    protected static final int MSG_GET_RTK_DEFAIL =1;
    protected static final int MSG_GET_DATA_RAW_STATUS =2;
    public static final String ISCLICKCANNEL ="isClickCannel";//是否点击了对话框上面的取消按钮
    public static final String ISFRAGMENT ="isFragment";//假如是fragment进行的连接，这边的不作反应
    private boolean isGetRTKSucc=false;
    private FrameLayout container;


    private static class MyHandler extends Handler {
        WeakReference<MainActivity> weakReference;

        private MyHandler(MainActivity activity) {
            weakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case MSG_AUTO_CONNECT:
                        activity.antoConnectLastDevice();
                        break;
                    case MSG_GET_RTK_DEFAIL://GETALL节点数据一直没有返回
                        activity.whenReadRtkDefail();
                        break;
                    case MSG_GET_DATA_RAW_STATUS:
                        //每隔1s发送命令获取数据回传状态
//                        if(DeviceManage.getInstance().isConnected()){
//                            String strCommand="GET,DEVICE.RAW.RESULT_STATUS\r\n";
//                            DeviceManage.getInstance().sendCommand(strCommand);
//                        }
//                        activity.myHandler.sendEmptyMessageDelayed(MSG_GET_DATA_RAW_STATUS,1000);
                        break;
                }
            }
        }
    }

    //自动连接上一次已经匹配的设备
    private void antoConnectLastDevice() {
        String address= SpUtils.obtain().getString(LAST_DEVICE);
        //显示已配对的蓝牙item
        bondedDevices = mBtAdatper.getBondedDevices();
        Iterator<BluetoothDevice> iterator= bondedDevices.iterator();
        while(iterator.hasNext()){
            BluetoothDevice bluetoothDevice=iterator.next();
            //自动连接上一次的蓝牙设备
            if(bluetoothDevice.getAddress().equals(address)){
                device=bluetoothDevice;
                //断开连接的时候才自动重连
                if(!DeviceManage.getInstance().isConnected()){
                    connectToServer();
                }
                return;
            }
        }
    }

    //连接成功或者失败
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showDeviceConnectResultStatus(DeviceUpdateEvent.DeviceConnectResultStatus event) {
        if(SpUtils.obtain().getBoolean(ISFRAGMENT,false))//是fragment连接成功的话，这里不执行
            return;
        if(event.isbSuccess()){
            whenConnectToServerSuccess();
        }else{
            whenConnecToServerDefail();
        }
    }

    //GETALL数据成功返回
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showGetRtkResultStatus(DeviceUpdateEvent.UpdateDialogGetRtkSuccessStatus event) {
        if(SpUtils.obtain().getBoolean(ISFRAGMENT,false))//是fragment连接成功的话，这里不执行
            return;
        whenReadRtkSuccess();
    }

    //断开设备，包括读取数据失败
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showDeviceDisConnectResultStatus(DeviceUpdateEvent.DeviceDisConnectResultStatus event) {
        if(SpUtils.obtain().getBoolean(ISFRAGMENT,false))//是fragment连接成功的话，这里不执行
            return;
        whenDeviceDisConnect();
    }

    //自动连接--不管是在哪里连接的，都交给MianActivity处理，假如是设置页连接成功的，直接传递device到这边连接
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void whenAutoConnect(DeviceUpdateEvent.AutoConnectEvent event) {
        //先进行断开，防止之前没有断开连接
        whenDeviceDisConnect();
        //蓝牙没有打开
        if (!mBtAdatper.isEnabled()) {
            return;
        }
        date = new Date();
        connectToServer();
    }

    //连接服务器成功，1.对话框状态显示 2.开始计时，判断是不是获取GETALL数据成功
    private void whenConnectToServerSuccess(){
        //当点击了取消按钮的时候，因为在不同的线程中，可能已经连接成功，在这里进行拦截
        if(SpUtils.obtain().getBoolean(ISCLICKCANNEL,false)){
            //这里不用把ISCLICKCANNEL置为false，在设置页面进行重置
            //showToast(R.string.toasst_connect_fail);
            DeviceManage.getInstance().disConnect();
            return;
        }
        if(connectioningDialogFragment!=null){
            connectioningDialogFragment.setProgress(50,"正在获取RTK状态......");
        }
        //目的是防止获取RTK时间过长，3s没有GTEALL OK则表示获取数据失败
        myHandler.sendEmptyMessageDelayed(MSG_GET_RTK_DEFAIL,9000);
    }

    //读取RTK信息成功 1.告诉设置页面 2更新对话框状态 3.保存当前连接成功的设备的信息，方便下次自动重连
    private void whenReadRtkSuccess() {
        if(SpUtils.obtain().getBoolean(ISCLICKCANNEL,false)){
            DeviceManage.getInstance().disConnect();
            return;
        }
        isGetRTKSucc=true;
        date = new Date();
        if(connectioningDialogFragment!=null && connectioningDialogFragment.isVisible()){
            connectioningDialogFragment.setProgress(100,"连接成功......");
            connectioningDialogFragment.dismissAllowingStateLoss();
        }

        //发送蓝牙的强度和地址给那边
        EventBus.getDefault().postSticky(new BluetoothInfoEvent(device));
        //保存最后一次连接的设备
        if (device != null) {
            tvDeviceName.setText(device.getName());
            SpUtils.obtain().save(LAST_DEVICE, device.getAddress());
        }
    }


    //连接服务器失败 1.告诉设置页面 2.对话框消失 3.断开服务器
    private void whenConnecToServerDefail() {
        dismissDialog();
        showToast(R.string.toasst_connect_fail);
    }

    //读取RTK信息失败，因为不知道怎么判断，采用大概8s没有连接，就表示读取RTK失败
    //1.消失对话框 2.断开连接
    private void whenReadRtkDefail() {
        if(SpUtils.obtain().getBoolean(ISFRAGMENT,false))//是fragment连接成功的话，这里不执行
            return;
        if(isGetRTKSucc){
            isGetRTKSucc=false;
            return;
        }
        DeviceManage.getInstance().setAutoDisconnect(false);
        DeviceManage.getInstance().disConnect();
        showToast(R.string.toast_read_rtk_defail);
        dismissDialog();
    }

    private void whenDeviceDisConnect() {
        dismissDialog();
        tvDeviceName.setText(R.string.text_no_device);
        showDataRawStatusDefail();
    }

    private void showDataRawStatusDefail() {
        tvSatelliteNum.setText("0/0");
        tvSolutionState.setText("0/0");
        tvSolutionState.setText("无数据");
        tvResultIp.setText("0.0.0.0");
        tvResultPort.setText("0");
        tvDelayTime.setText("无数据");
    }

    //显示下面的定位信息
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showUpdateLocationResultStatus(DeviceUpdateEvent.UpdateLocationResultStatus event) {
        showReceiveLocationData();
    }

    //显示下面的数据回传信息--GETALL成功
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showAnalysisGNSSDataSuccess(DeviceUpdateEvent.UpdateDialogGetRtkSuccessStatus event) {
        if (!DeviceManage.getInstance().isConnected())
            return;
        tvResultIp.setText(deviceInfo.surveyInfo.mResultIp);
        tvResultPort.setText(deviceInfo.surveyInfo.mResultPort);
    }

    //显示数据回传状态
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showUpdateDataRawResultStatus(DeviceUpdateEvent.UpdateDialogGetDataRawResultSuccessStatus event) {
        showDataRawStatusSucc();
    }

    private void showDataRawStatusSucc() {
//        0430：模块在初始化
//        0431：网络已准备好
//        0432：模块初始化失败
//        0433：正在连接服务器
//        0434：连接服务器失败
//        0435：连上服务器
////      0436：设置（Ntrip）协议失败
//        0437：正在传输数据
//        0438：已断开
//        0440：模块关闭
        if(deviceInfo.surveyInfo.mResultStatus==null)
            return;
        int status=Integer.parseInt(deviceInfo.surveyInfo.mResultStatus);
        String dataStatus="";
        switch (status){
            case 430:
                dataStatus="模块在初始化";
                break;
            case 431:
                dataStatus="网络已准备好";
                break;
            case 432:
                dataStatus="模块初始化失败";
                break;
            case 433:
                dataStatus="正在连接服务器";
                break;
            case 434:
                dataStatus="连接服务器失败";
                break;
            case 435:
                dataStatus="连上服务器";
                break;
            case 436:
                dataStatus="设置（Ntrip）协议失败";
                break;
            case 437:
                dataStatus="正在传输数据";
                break;
            case 438:
                dataStatus="已断开";
                break;
            case 440:
                dataStatus="模块关闭";
                break;
            default:
                dataStatus="异常";
                break;
        }
        tvDataResultStatus.setText(dataStatus);
    }

    private void showReceiveLocationData() {
        int totalSatelites = (int) geoLocationData.getSateInfoList().getSateInfoList().size();
        int userSatelites = geoLocationData.getSateInfoList().getGpsInLock() + geoLocationData.getSateInfoList().getGlonassInLock()
                + geoLocationData.getSateInfoList().getGaileoInLock() + geoLocationData.getSateInfoList().getBdInLock();
        tvSatelliteNum.setText(getString(R.string.satellite_num, userSatelites,totalSatelites));
        // 质量因子——0=未定位，1=GPS单点定位固定解，2=差分定位，3=PPS解；4=RTK固定解；5=RTK浮点解；6=估计值；
        // 7=手工输入模式；8=模拟模式；
        String name = "";
        switch (geoLocationData.getSolutionType().swigValue()){
            case -1:
                name=getString(R.string.text_quality_indicator_no_data);
                break;
            case 0:
                name=getString(R.string.text_quality_indicator_no_location);
                break;
            case 1:
                name=getString(R.string.text_quality_indicator_single);
                break;//Differential positioning
            case 2:
                name=getString(R.string.text_quality_indicator_diff_posi);
                break;
            case 3:
                name=getString(R.string.text_quality_indicator_pps);
                break;
            case 4:
                name=getString(R.string.text_quality_indicator_rtk_fix);
                break;
            case 5:
                name=getString(R.string.text_quality_indicator_rtk_float);
                break;
            case 6:
                name=getString(R.string.text_quality_indicator_rtk_estimate);
                break;
            case 7:
                name=getString(R.string.text_quality_indicator_rtk_input);
                break;
            case 8:
                name=getString(R.string.text_quality_indicator_simulation);
                break;

        }
        tvSolutionState.setText(name);
        tvDelayTime.setText(geoLocationData.getAgeOfDiff()+"s");
    }


    @Override
    public void initData() {
        geoLocationData = GeoLocationData.getInstance();
        deviceInfo= CommandParseManage.getInstance().getDeviceInfo();
        simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.CHINA);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//找到设备
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始扫描
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索完成
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变--配对、未配对、正在配对
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙开启关闭
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);//信号强度
        blueToothBroadcastReceiver= BlueToothBroadcastReceiver.getSingleton();
        registerReceiver(blueToothBroadcastReceiver, filter);
        mBtAdatper = BluetoothAdapter.getDefaultAdapter();
        BlueToothDeviceAdapter adapter = new BlueToothDeviceAdapter(this, R.layout.layout_bluetooth_device_list_item);
        operateBlueTooth= new BlueToothInit(this,mBtAdatper, adapter);

        //进来先判断是不是连接状态,没有进入设置页面，一直在主页面，显示连接设备名字
        if (DeviceManage.getInstance().isConnected()) {
            String device=DeviceManage.getInstance().getDeviceName();
            tvDeviceName.setText(device.substring(0,device.lastIndexOf("|")));
        }

        //3s后如果设备没有连接自动连接上一次成功匹配过的设备
        myHandler =new MyHandler(this);
        myHandler.sendEmptyMessageDelayed(MSG_AUTO_CONNECT,3000);

        myHandler.sendEmptyMessage(MSG_GET_DATA_RAW_STATUS);

    }

    //连接服务器
    public void connectToServer(){
        if (!mBtAdatper.isEnabled()) {
            showToast(R.string.open_bluetooth);
            return;
        }
        if(device!=null){
            //开始配对
            if(operateBlueTooth.getBondState(device)){//已经成功匹配过
                //真正开始连接
                isSendSuccessFirst=false;
                startRealConnect(device);
                //开始显示连接对话框
                showConnectioningDialog();
            }
        }else{
            showToast(R.string.toasst_connect_fail);
        }
    }

    //真正进行连接
    private void startRealConnect(BluetoothDevice device) {
        SpUtils.obtain().save(ISFRAGMENT,false);
        SpUtils.obtain().save(ISCLICKCANNEL,false);
        String strDeviceName = String.format("%s|%s", device.getName(), device.getAddress());
        DeviceManage.getInstance().setSelectedDevice(strDeviceName);
        DeviceManage.getInstance().connect();
    }

    //显示连接对话框
    public void showConnectioningDialog(){
        //开始显示连接对话框
        connectioningDialogFragment = ConnectioningDialogFragment.getSingleton();
        if(!connectioningDialogFragment.isAdded()){
            connectioningDialogFragment.setCancelable(false);
            connectioningDialogFragment.show(getFragmentManager(), "connectioning");
            connectioningDialogFragment.setClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //点击取消--对话框消息+断开服务器+移除全部事件
                    DeviceManage.getInstance().setAutoDisconnect(false);
                    SpUtils.obtain().save(ISCLICKCANNEL,true);
                    dismissDialog();
                    DeviceManage.getInstance().disConnect();
                    showToast(R.string.connect_fail);
                }
            });
        }
    }

    //消失对话框
    public void dismissDialog(){
        if (connectioningDialogFragment != null && connectioningDialogFragment.isVisible()) {
            connectioningDialogFragment.dismissAllowingStateLoss();
        }
    }

    //设置页面通知主页连接成功的设备名称
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showDeviceName(ShowDeviceNameEvent event) {
        String name;
        if(event.getDevice()==null){
            name=getString(R.string.text_no_device);
            showDataRawStatusDefail();

        }else{
            name=event.getDevice().getName();
            device=event.getDevice();
        }
        tvDeviceName.setText(name);
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_activity_main;
    }

    @Override
    public void initView() {
        tvDeviceName=(TextView) findViewById(R.id.device_name);
        View titleBar = findViewById(R.id.title_bar);
        container = findViewById(R.id.container);
        titleBar.setVisibility(View.VISIBLE);


        llEquipmentCommunicationSetup=findViewById(R.id.ll_equipment_communication_setup);
        llSetupGprs = (LinearLayout)findViewById( R.id.ll_setup_gprs );
        llSetupWifi = (LinearLayout)findViewById( R.id.ll_setup_wifi );
        llSetupSurveyStation = (LinearLayout)findViewById( R.id.ll_setup_survey_station );
        llSetupTransformation = (LinearLayout)findViewById( R.id.ll_setup_transformation );
        llSetupOther = (LinearLayout)findViewById( R.id.ll_setup_other );
        llSetupDebug = (LinearLayout)findViewById( R.id.ll_setup_debug );
        llSetupAbout = (LinearLayout)findViewById( R.id.ll_setup_about);
        llEquipmentInformation=findViewById(R.id.ll_equipment_information);
        llSatelliteLocateInformation =findViewById(R.id.ll_satellite_locate_information);
        llSatelliteForm =findViewById(R.id.ll_satellite_form);
        llSatelliteMap =findViewById(R.id.ll_satellite_map);
        llSaveConfig =findViewById(R.id.ll_save_config);
        llApplyConfig =findViewById(R.id.ll_apply_config);

        tvSatelliteNum =findViewById(R.id.tv_satellite_num);
        tvSolutionState =findViewById(R.id.tv_solution_state);
        tvDelayTime =findViewById(R.id.tv_delay_time);
        tvDataResultStatus =findViewById(R.id.tv_data_result_status);
        tvResultIp =findViewById(R.id.tv_result_ip);
        tvResultPort =findViewById(R.id.tv_result_port);


        llEquipmentCommunicationSetup.setOnClickListener(this);
        llSetupGprs.setOnClickListener(this);
        llSetupWifi.setOnClickListener(this);
        llSetupSurveyStation.setOnClickListener(this);
        llSetupTransformation.setOnClickListener(this);
        llSetupOther.setOnClickListener(this);
        llSetupDebug.setOnClickListener(this);
        llSetupAbout.setOnClickListener(this);
        llEquipmentInformation.setOnClickListener(this);
        llSatelliteLocateInformation.setOnClickListener(this);
        llSatelliteForm.setOnClickListener(this);
        llSatelliteMap.setOnClickListener(this);
        llSaveConfig.setOnClickListener(this);
        llApplyConfig.setOnClickListener(this);
    }

    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_equipment_communication_setup:
                goToNextFragment(EquipmentCommunicationSetupFragment.newInstance());
                break;
            case R.id.ll_setup_gprs:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupGprsFragment.newInstance());
                break;
            case R.id.ll_setup_wifi:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupWifiFragment.newInstance());
                break;
            case R.id.ll_setup_survey_station:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupSurveyStationFragment.newInstance());
                break;
            case R.id.ll_setup_transformation:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupTransformationFragment.newInstance());
                break;
            case R.id.ll_setup_other:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupOtherFragment.newInstance());
                break;
            case R.id.ll_setup_debug:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SetupDebugFragment.newInstance());
                break;
            case R.id.ll_setup_about:
                goToNextFragment(SetupAboutFragment.newInstance());
                break;
            case R.id.ll_equipment_information:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this, R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(EquipmentInformationFragment.newInstance());
                break;
            case R.id.ll_satellite_locate_information:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SatelliteLocateInformationFragment.newInstance());
                break;
            case R.id.ll_satellite_form:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SatelliteFormFragment.newInstance());
                break;
            case R.id.ll_satellite_map:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(SatelliteMapFragment.newInstance());
                break;
            case R.id.ll_save_config:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                showSaveConfigDidlog();
                break;
            case R.id.ll_apply_config:
                if(!DeviceManage.getInstance().isConnected()){
                    Toast.makeText(this,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
                    return;
                }
                goToNextFragment(ApplyConfigFragment.newInstance());
                break;
        }
    }

    public void showSaveConfigDidlog(){
        //开始显示连接对话框
        saveConfigFragment = SaveConfigFragment.newInstance();
        if(!saveConfigFragment.isAdded()){
            saveConfigFragment.setCancelable(false);
            saveConfigFragment.show(getFragmentManager(), "saveConfig");
        }
    }


    @Override
    public void onDestroy() {
        unregisterReceiver(blueToothBroadcastReceiver);
        super.onDestroy();
    }

}
